---
title: Custom APIs
---

import { Aside } from "@astrojs/starlight/components";

On startup TrailBase will automatically load any WASM component, i.e. `*.wasm`
files in `traildepot/wasm`.
This can be used to implement arbitrary HTTP APIs with custom handlers.

## Example HTTP Endpoint

The following TypeScript WASM example illustrates a few things:

* How to register a parameterized route with `{table}`.
* How to query the database.
* How to return an HTTP error.

```ts
import { defineConfig } from "trailbase-wasm";
import { Request, HttpError, HttpHandler, StatusCode } from "trailbase-wasm/http";
import { query } from "trailbase-wasm/db";

async function handler(req: Request): Promise<string> {
  const table = req.getPathParam("table");
  if (table) {
    const rows = await query(`SELECT COUNT(*) FROM ${table}`, [])
    return `entries: ${rows[0][0]}`;
  }

  throw new HttpError(
      StatusCode.BAD_REQUEST, "Missing '?table=' search query param");
}

export default defineConfig({
  httpHandlers: [ HttpHandler.get("/test/{table}", handler) ],
});
```

More examples can be found in the repository under `examples/wasm-guest-ts/`,
`examples/wasm-guest-js/` and `examples/wasm-guest-rust/`.
